package com.fy.service.imbusiness.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.exception.NacosException;
import com.fy.common.dto.UserAndGroupSearchDto;
import com.fy.common.vo.ImServerHost;
import com.fy.framework.common.model.R;
import com.fy.framework.component.config.LocaleMessage;
import com.fy.service.service.SkImCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhshuo
 * @date 2021/12/13 13:49
 */
@Slf4j
@RestController
@Api(tags = "通用接口")
@RequestMapping("/common")
public class SkImCommonController {
    //这里可以设置tcp服务的端口号
    @Value("${netty.server.cer.port}")
    private int port = 9912;
    @Value("${netty.server.cer.webport}")
    private int webport = 9703;

    @Autowired
    LocaleMessage localeMessage;

    @Autowired
    SkImCommonService commonService;

    @Autowired
    DiscoveryClient discoveryClient;

    /**
     * 用户搜索
     * @return List<用户>
     */
    @PostMapping("search")
    @ApiOperation("用户搜索")
    public R<?> userSearch(@RequestBody UserAndGroupSearchDto  searchDto){
        if(StringUtils.isBlank(searchDto.getKey())){
            return R.failedAlter(localeMessage.getMessage("im.common.sendparameterError"));
        }
        return commonService.userSearch(searchDto);
    }

    @PostMapping("getServer")
    @ApiOperation("获取IM Server的连接地址")
    public R<ImServerHost> getServer(@RequestBody @ApiParam(name="type",value="TCP或者SOCKET")  JSONObject type) throws NacosException {
        List<ServiceInstance> instances = discoveryClient.getInstances("fy-im-server");
        String typeString = type.getString("type");
        List<String> collect = instances.stream().map(ServiceInstance::getHost).collect(Collectors.toList());
        return R.success(new ImServerHost().setHosts(collect).setPort(typeString.equalsIgnoreCase("TCP")?port:webport));
    }

}
